<script setup lang="ts">
defineOptions({
  name: "ALL_FAB_PROVISION_CRAFT"
});
import { ref, reactive, onMounted, onUnmounted, nextTick, computed } from "vue";
import * as echarts from "echarts";
import { Right } from "@px-ui/icons-vue";
import ReTeleport from "@/components/ReTeleport";
import search from "../components/search.vue";
import { useRouter, useRoute } from "vue-router";
import { useRouterStoreHook } from "@/store/modules/router";
import { querySupplyConsume, queryFlow, queryTotalConsume, queryTechnologyList, queryProductList, queryLotList, queryWaferList } from "@/api/craft";
import { useElementSize } from "@vueuse/core";

const route = useRoute();
const router = useRouter();
const routerStore = useRouterStoreHook();
const pageRef = ref();
const pageContentRef = ref();
const { width: pageContentWidth } = useElementSize(pageContentRef);
const { height: pageHeight } = useElementSize(pageRef);
const chart = ref(null);
const loading = ref(null);
const routeTypeList = ref([]);
const layerList = ref([]);
const runLayerList = ref([]);
const dataTypes = ref<Array<string>>(["实际值"]);
const searchRef = ref<InstanceType<typeof search> | null>(null);
const queryRef = ref(null);
const { height: formHeight } = useElementSize(queryRef);
const tableHeight = computed(() => Math.floor(pageHeight.value - formHeight.value - 62));
const queryParams = reactive({
  technology: "",
  product: "",
  lot: "",
  wafer: "",
  area: ""
});
const defaultSearchParams = reactive({
  startTime: "",
  endTime: "",
  parameter: "",
  period: "week",
  parameterName: ""
});
const rules = reactive({
  wafer: [{ required: false, trigger: "change", message: "请输入" }]
});
const totalConsume = reactive({
  value: "",
  unit: ""
});
const filterParams = reactive({
  groupType: "STEP", // STEP ROUTE LAYER
  routes: []
});
const technologyList = ref([]);
const productList = ref([]);
const lotList = ref([]);
const waferList = ref([]);
const lotLoading = ref(false);
const waferLoading = ref(false);
const tableData = ref([]);

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (column.property == "dataChart") {
    if (rowIndex == 0) {
      //row.isFirst
      return {
        rowspan: tableData.value.length, // 按照layer合并 row.layerGap
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
  if (filterParams.groupType == "STEP" && column.property == "layer") {
    if (row.isFirst) {
      return {
        rowspan: row.layerGap, // 按照layer合并
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};
const rowClassName = ({ row, rowIndex }) => {
  if (filterParams.groupType == "STEP") {
    if (row.isFirst) {
      let index = layerList.value.findIndex(v => v.layer == row.layer);
      if (index % 2 == 0) {
        return "layer-row layer-row-even";
      }
      return "layer-row";
    }
  } else {
    if (rowIndex % 2 == 0) {
      return "layer-row layer-row-even";
    }
    return "layer-row";
  }
};
const cellClassName = ({ row, column, rowIndex, columnIndex }) => {
  if (filterParams.groupType == "STEP" && column.property == "layer") {
    return "layer-column";
  }
  if (filterParams.groupType == "LAYER" && column.property == "layer") {
    return "s-layer-column";
  }
  if (column.property == "routeType") {
    return "route-type-column";
  }

  if (column.property == "dataChart" && row.isFirst) {
    return "data-chart-column";
  }
};
let chartList = [];
let myChart = null;

const getClassName = area => {
  let cn = "";
  if (area == "PVD后段") {
    cn = "pvd-back";
  } else {
    cn = area.toLocaleLowerCase();
  }
  return cn;
};
const getGridData = () => {
  // if (filterParams.groupType == "STEP") {
  //   let grid = [];
  //   runLayerList.value.forEach((v, i) => {
  //     let shotIndex = layerList.value.findIndex(item => item.layerId == v.layer);
  //     v.layerGap = layerList.value[shotIndex].layerGap;
  //     grid.push({
  //       left: -1,
  //       height: (layerList.value[shotIndex].layerGap / tableData.value.length) * 100 + "%",
  //       top: 0
  //     });
  //   });
  //   grid.forEach((v, i) => {
  //     if (i == 0) {
  //       v.top = 0;
  //     } else {
  //       let gap = 0;
  //       for (let j = 0; j < i; j++) {
  //         gap += runLayerList.value[j].layerGap;
  //       }
  //       grid[i].top = (gap / tableData.value.length) * 100 + "%";
  //     }
  //   });
  //   grid.push({
  //     left: -1,
  //     height: "100%",
  //     top: 0
  //   });
  //   return grid;
  // } else {
  //   return {
  //     left: -1,
  //     height: "100%",
  //     top: 0
  //   };
  // }
  return {
    left: -1,
    height: "100%",
    top: 0
  };
};
const getyAxisData = chartData => {
  // if (filterParams.groupType == "STEP") {
  //   let yAxiasList = [];
  //   chartData.barInfo.forEach((v, i) => {
  //     yAxiasList.push({
  //       type: "category",
  //       gridIndex: i,
  //       axisPointer: {
  //         type: "shadow"
  //       },
  //       axisLabel: {
  //         show: false
  //       },
  //       axisTick: {
  //         show: false
  //       },
  //       axisLine: {
  //         show: false
  //       },
  //       show: false,
  //       data: v.barList.map(item => item.name),
  //       inverse: true
  //     });
  //   });
  //   yAxiasList.push({
  //     type: "category",
  //     gridIndex: chartData.barInfo.length,
  //     axisPointer: {
  //       type: "shadow"
  //     },
  //     axisLabel: {
  //       show: false
  //     },
  //     axisTick: {
  //       show: false
  //     },
  //     axisLine: {
  //       show: false
  //     },
  //     show: false,
  //     data: chartData.lineInfo.yAxis,
  //     inverse: true
  //   });
  //   return yAxiasList;
  // } else {
  //   return {
  //     type: "category",
  //     axisLabel: {
  //       show: false
  //     },
  //     axisTick: {
  //       show: false
  //     },
  //     axisLine: {
  //       show: false
  //     },
  //     show: false,
  //     data: chartData.barInfo.map(item => item.name),
  //     inverse: true
  //   };
  // }
  return {
    type: "category",
    axisLabel: {
      show: false
    },
    axisTick: {
      show: false
    },
    axisLine: {
      show: false
    },
    show: false,
    data: chartData.barInfo.map(item => item.name),
    inverse: true
  };
};
// 获取最大值和最小值
const getMaxMinValue = chartData => {
  let values = [];
  // if (filterParams.groupType == "STEP") {
  //   chartData.barInfo.forEach(v => {
  //     if (dataTypes.value.includes("实际值")) {
  //       let consumeValues = v.barList.map(item => item.consumeValue);
  //       values.push(...consumeValues);
  //     }
  //     if (dataTypes.value.includes("供给值")) {
  //       let supplyValues = v.barList.map(item => item.supplyValue);
  //       values.push(...supplyValues);
  //     }
  //   });
  // } else {
  //   if (dataTypes.value.includes("实际值")) {
  //     let consumeValues = chartData.barInfo.map(item => item.consumeValue);
  //     values.push(...consumeValues);
  //   }
  //   if (dataTypes.value.includes("供给值")) {
  //     let supplyValues = chartData.barInfo.map(item => item.supplyValue);
  //     values.push(...supplyValues);
  //   }
  // }

  if (dataTypes.value.includes("实际值")) {
    let consumeValues = chartData.barInfo.map(item => item.consumeValue);
    values.push(...consumeValues);
  }
  if (dataTypes.value.includes("供给值")) {
    let supplyValues = chartData.barInfo.map(item => item.supplyValue);
    values.push(...supplyValues);
  }
  if (dataTypes.value.includes("设定值")) {
    values.push(...chartData.lineInfo.value);
  }

  return {
    max: Math.max(...values),
    min: Math.min(...values),
    allValues: values
  };
};
const getxAxisData = chartData => {
  let boundary = getMaxMinValue(chartData);
  // if (filterParams.groupType == "STEP") {
  //   let xAxiasList = [];
  //   let lens = chartData.barInfo.length + 1; // 多了个line，后续不要再判断
  //   for (let i = 0; i < lens; i++) {
  //     xAxiasList.push({
  //       gridIndex: i,
  //       type: "value",
  //       name: "",
  //       min: 0,
  //       max: boundary.max,
  //       // interval: 50,
  //       axisLabel: {
  //         show: false,
  //         formatter: "{value}"
  //       },
  //       position: "top"
  //     });
  //   }
  //   return xAxiasList;
  // } else {
  //   return {
  //     type: "value",
  //     name: "",
  //     min: 0,
  //     max: boundary.max,
  //     // interval: 50,
  //     axisLabel: {
  //       show: false,
  //       formatter: "{value}"
  //     },
  //     position: "top"
  //   };
  // }
  return {
    type: "value",
    name: "",
    min: 0,
    max: boundary.max,
    // interval: 50,
    axisLabel: {
      show: false,
      formatter: "{value}"
    },
    position: "top"
  };
};
const getSeriesData = chartData => {
  // 实际值、供给值、设定值  consumeValue: v.consumeValue, supplyValue: v.supplyValue, setValue: v.setValue,
  let consumeList = [],
    supplyList = [],
    setList = [];
  // if (filterParams.groupType == "STEP") {
  //   chartData.barInfo.forEach((v, index) => {
  //     let valueList = v.barList.map(item => item.consumeValue);
  //     if (dataTypes.value.includes("实际值")) {
  //       consumeList.push({
  //         name: "实际值",
  //         type: "bar",
  //         color: "#3B82F6",
  //         data: valueList,
  //         label: {
  //           show: true, // 显示标签
  //           position: "right", // 标签位置
  //           formatter: "{c}" // 标签格式器，{c} 代表数据值
  //         },
  //         barWidth: 12,
  //         xAxisIndex: index,
  //         yAxisIndex: index
  //       });
  //     }
  //   });
  //   chartData.barInfo.forEach((v, index) => {
  //     let valueList = v.barList.map(item => item.supplyValue);
  //     if (dataTypes.value.includes("供给值")) {
  //       supplyList.push({
  //         name: "供给值",
  //         type: "bar",
  //         color: "#FFCA45",
  //         data: valueList,
  //         label: {
  //           show: true, // 显示标签
  //           position: "right", // 标签位置
  //           formatter: "{c}" // 标签格式器，{c} 代表数据值
  //         },
  //         barWidth: 12,
  //         xAxisIndex: index,
  //         yAxisIndex: index
  //       });
  //     }
  //   });
  //   if (dataTypes.value.includes("设定值")) {
  //     setList.push({
  //       name: "设定值",
  //       type: "line",
  //       step: "middle", // 使用阶梯状的线条middle end
  //       color: "#FF4545",
  //       data: chartData.lineInfo.value,
  //       xAxisIndex: chartData.barInfo.length,
  //       yAxisIndex: chartData.barInfo.length
  //     });
  //   }
  // } else {
  //   if (dataTypes.value.includes("实际值")) {
  //     consumeList.push({
  //       name: "实际值",
  //       type: "bar",
  //       color: "#3B82F6",
  //       data: chartData.barInfo.map(item => item.consumeValue),
  //       label: {
  //         show: true, // 显示标签
  //         position: "right", // 标签位置
  //         formatter: "{c}" // 标签格式器，{c} 代表数据值
  //       },
  //       barWidth: 12
  //     });
  //   }
  //   if (dataTypes.value.includes("供给值")) {
  //     consumeList.push({
  //       name: "供给值",
  //       type: "bar",
  //       color: "#FFCA45",
  //       data: chartData.barInfo.map(item => item.supplyValue),
  //       label: {
  //         show: true, // 显示标签
  //         position: "right", // 标签位置
  //         formatter: "{c}" // 标签格式器，{c} 代表数据值
  //       },
  //       barWidth: 12
  //     });
  //   }
  //   if (dataTypes.value.includes("设定值")) {
  //     setList.push({
  //       name: "设定值",
  //       type: "line",
  //       step: "middle", // 使用阶梯状的线条middle end
  //       color: "#FF4545",
  //       data: chartData.lineInfo.value
  //     });
  //   }
  // }
  if (dataTypes.value.includes("实际值")) {
    consumeList.push({
      name: "实际值",
      type: "bar",
      color: "#3B82F6",
      data: chartData.barInfo.map(item => item.consumeValue),
      label: {
        show: true, // 显示标签
        position: "right", // 标签位置
        formatter: "{c}" // 标签格式器，{c} 代表数据值
      },
      barWidth: 12
    });
  }
  if (dataTypes.value.includes("供给值")) {
    consumeList.push({
      name: "供给值",
      type: "bar",
      color: "#FFCA45",
      data: chartData.barInfo.map(item => item.supplyValue),
      label: {
        show: true, // 显示标签
        position: "right", // 标签位置
        formatter: "{c}" // 标签格式器，{c} 代表数据值
      },
      barWidth: 12
    });
  }
  if (dataTypes.value.includes("设定值")) {
    setList.push({
      name: "设定值",
      type: "line",
      step: "middle", // 使用阶梯状的线条middle end
      color: "#FF4545",
      data: chartData.lineInfo.value
    });
  }
  return [...consumeList, ...supplyList, ...setList];
};
// 画一个刻度在table header 上
let rulerChart = null;
const drawRulerChart = chartData => {
  if (rulerChart !== null && rulerChart !== undefined) {
    rulerChart.dispose();
  }
  rulerChart = echarts.init(document.getElementById("ruler-chart"));
  let boundary = getMaxMinValue(chartData);
  var option = {
    tooltip: {
      show: false
    },
    grid: {
      left: 0,
      top: 30
    },

    yAxis: {
      type: "category",
      axisPointer: {
        type: "shadow"
      },
      axisLabel: {
        show: true
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
      show: false,
      data: boundary.allValues
    },
    axisLabel: {
      formatter: "{value}"
    },
    xAxis: {
      type: "value",
      // name: "kwh",
      // nameLocation: "end",
      min: 0,
      max: boundary.max,
      position: "top",
      axisLabel: {
        align: "left",
        verticalAlign: "middle",
        fontSize: 13,
        fontWeight: "bold"
      },
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
        // lineStyle: {
        //   type: 'dashed', // 虚线样式
        //   color: 'rgba(255, 255, 255, 0.15)' // 虚线颜色
        // }
      }
    },
    series: [
      {
        name: "值",
        type: "bar",
        color: "transparent",
        data: boundary.allValues,
        label: {
          show: false, // 显示标签
          position: "right", // 标签位置
          formatter: "{c}" // 标签格式器，{c} 代表数据值
        },
        barWidth: 0
      }
    ]
  };
  // 使用刚指定的配置项和数据显示图表。
  rulerChart.setOption(option);
};
// 初始所有chart
const initChart = chartData => {
  // if (chartList[layer] !== null && chartList[layer] !== undefined) {
  //   chartList[layer].dispose() //销毁
  // }
  // chartList[layer] = echarts.init(document.getElementById('chart_' + layer));
  if (myChart !== null && myChart !== undefined) {
    myChart.dispose();
  }
  myChart = echarts.init(document.getElementById("chart"));

  // 指定图表的配置项和数据
  var option = {
    tooltip: {
      //show: false,
      // appendToBody: true,
      confine: true,
      extraCssText: "z-index: 9999999;",
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999"
        }
      }
    },

    grid: getGridData(),

    yAxis: getyAxisData(chartData),
    axisLabel: {
      formatter: "{value}"
    },
    xAxis: getxAxisData(chartData),
    series: getSeriesData(chartData)
  };
  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
};

// const getFlowInfo = async params => {
//   let p = {
//     startTime: "2024-06-01 00:00:00",
//     endTime: "2024-07-11 23:59:59",
//     parameter: "GC01BG01AV13",
//     technology: "28nm",
//     product: "40MPU-PRODUCT-01",
//     lot: "YPP001384",
//     wafer: "YPP001384#19",
//     groupType: "STEP"
//   };
//   let res = await queryFlow(p);
//   tableData.value = res;
//   rebuildData();
// };
// 处理table by layer 数据
const rebuildData = () => {
  routeTypeList.value = tableData.value.reduce((prev, curr) => {
    let has = prev.some(v => v.routeType == curr.routeType);
    if (!has && curr.routeType) {
      prev.push(curr);
    }
    return prev;
  }, []);
  // filterParams.routes = routeList.value.map(v => v.routeType);
  layerList.value = tableData.value.reduce((prev, curr) => {
    let has = prev.some(v => v.layer == curr.layer);
    if (!has && curr.layer) {
      prev.push(curr);
    }
    return prev;
  }, []);
  tableData.value.forEach((v, k) => {
    let layer = v.layer;
    let layers = tableData.value.filter(v => v.layer == layer);
    v.layerGap = layers.length;
    let curr = layerList.value.filter(item => item.layer == layer);
    v.isFirst = !!(v.step == curr[0].step); // 当前的stepid和layerId 与 layerList一致
  });
};
const buildChartData = (originData, type) => {
  if (!originData || !originData.length) {
    if (rulerChart !== null && rulerChart !== undefined) {
      rulerChart.dispose();
    }
    return;
  }
  let chartData = {
    barInfo: [], //柱状图信息
    lineInfo: {
      // 阶梯折线图信息
      yAxis: [],
      value: []
    }
  };
  runLayerList.value = originData.reduce((prev, curr) => {
    let has = prev.some(v => v.layer == curr.layer);
    if (!has && curr.layer) {
      prev.push({ ...curr, layerId: curr.layer, routeId: curr.route, stepId: curr.step });
    }
    return prev;
  }, []);
  // if (type == "STEP") {
  //   let barList = [];
  //   runLayerList.value.forEach((layerItem, index) => {
  //     let obj = {
  //       layer: layerItem.layer,
  //       barList: []
  //     };
  //     originData.forEach(v => {
  //       if (index == 0) {
  //         chartData.lineInfo.yAxis.push(v.step);
  //         chartData.lineInfo.value.push(v.setValue);
  //       }
  //       if (layerItem.layer == v.layer) {
  //         obj.barList.push({
  //           name: v.step,
  //           consumeValue: v.consumeValue,
  //           supplyValue: v.supplyValue,
  //           setValue: v.setValue
  //         });
  //       }
  //     });
  //     barList.push(obj);
  //   });
  //   chartData.barInfo = barList;
  // }
  let barList = [];
  originData.forEach(v => {
    let name = "";
    if (type == "STEP") {
      name = v.stepName;
    }
    if (type == "ROUTE") {
      name = v.routeType;
    }
    if (type == "LAYER") {
      name = v.layer;
    }
    chartData.lineInfo.yAxis.push(name); // layer - route1
    chartData.lineInfo.value.push(v.setValue);
    barList.push({
      name,
      consumeValue: v.consumeValue,
      supplyValue: v.supplyValue,
      setValue: v.setValue
    });
  });
  chartData.barInfo = barList;
  setTimeout(() => {
    initChart(chartData);
    drawRulerChart(chartData);
  }, 500);
};
const getTotalConsume = async params => {
  // let p = {
  //   startTime: "2024-06-01 00:00:00",
  //   endTime: "2024-07-11 23:59:59",
  //   parameter: "GC01BG01AV13",
  //   technology: "28nm",
  //   product: "40MPU-PRODUCT-01",
  //   lot: "YPP001384",
  //   wafer: "YPP001384#19",
  //   groupType: "STEP"
  // };
  let res = await queryTotalConsume(params);
  totalConsume.value = res.value;
  totalConsume.unit = res.unit;
};
const getSupplyConsume = async params => {
  // by layer list
  // let p = {
  //   startTime: "2024-06-01 00:00:00",
  //   endTime: "2024-07-19 23:59:59",
  //   parameter: "EL01MML01AV01", // EL01IL01AV01
  //   technology: "28nm",
  //   product: "40MPU-PRODUCT-01",
  //   lot: "YPP001384",
  //   wafer: "YPP001384#19",
  //   groupType: filterParams.groupType
  // };
  try {
    loading.value = true;
    let res = await querySupplyConsume(params);
    loading.value = false;
    let originData = res.dataList;
    tableData.value = originData;
    if (filterParams.groupType == "ROUTE" || filterParams.groupType == "LAYER") {
      routeTypeList.value = [];
      layerList.value = [];
    } else {
      rebuildData();
    }
    buildChartData(originData, filterParams.groupType);
  } catch (error) {
    loading.value = false;
  }
};
const searchChangeHandler = async (params?: Record<string, any>, types?: Array<any>) => {
  if (types.length == dataTypes.value.length) {
    dataTypes.value = types;
    await nextTick();
    searchAction(false);
  }
};
const searchSelectChange = val => {
  defaultSearchParams.parameterName = val.name;
};
const areaChange = item => {
  queryParams.area = item;
  searchAction(false);
};

const typeChange = async (types?: Array<any>) => {
  dataTypes.value = types;
  await nextTick();
  queryRef.value?.validate(async (valid, fields) => {
    if (valid) {
      buildChartData(tableData.value, filterParams.groupType);
    }
  });
};

const searchAction = isChange => {
  // 2个接口
  queryRef.value?.validate(async (valid, fields) => {
    if (valid) {
      const className = routerStore.getSubject !== "ALL" ? routerStore.getSubject : "";
      const p = searchRef.value.getParams();
      if (!p.parameter) {
        return;
      }
      const params = { ...queryParams, ...p, className, ...filterParams };
      if (params.area == "全部") {
        params.area = "";
      }
      // wafer 工艺流程
      // getFlowInfo(params);
      // 详细耗量
      getSupplyConsume(params);
      if (!isChange) {
        getTotalConsume(params);
      }
    } else {
      console.log("query submit!", fields);
    }
  });
};
const resetQuery = () => {
  queryParams.technology = "";
  queryParams.product = "";
  queryParams.lot = "";
  queryParams.wafer = "";
  tableData.value = [];
  routeTypeList.value = [];
  layerList.value = [];
  if (rulerChart !== null && rulerChart !== undefined) {
    rulerChart.dispose();
  }
};
const groupTypeChange = () => {
  // routes默认值修改
  // filterParams.routes = routeList.value.map(v => v.routeId);
  searchAction(true);
};
const getTechlogyList = async () => {
  let res: any = await queryTechnologyList();
  technologyList.value = res;
  // queryParams.technology = route.query.technology || "";
};
const getProductList = async () => {
  let res: any = await queryProductList();
  productList.value = res;
  // queryParams.product = route.query.product || "";
  // queryParams.lot = route.query.lot || "";
  // queryParams.wafer = route.query.wafer || "";
};
const getLotList = async name => {
  setTimeout(async () => {
    if (name) {
      lotLoading.value = true;
      let res: any = await queryLotList({ lotName: name });
      lotLoading.value = false;
      lotList.value = res.map(item => ({ label: item.name, value: item.code }));
    }
  }, 500);
};
const getWaferList = async name => {
  setTimeout(async () => {
    if (name) {
      waferLoading.value = true;
      let res: any = await queryWaferList({ waferName: name });
      waferLoading.value = false;
      waferList.value = res.map(item => ({ label: item.name, value: item.code }));
    }
  }, 500);
};
const daynamicTableData = computed(() =>
  filterParams.groupType == "STEP" ? tableData.value : filterParams.groupType == "ROUTE" ? routeTypeList.value : layerList.value
);
const chartWidth = computed(() => {
  let w = 800;
  if (filterParams.groupType == "STEP") {
    let t = 150 + 120 + routeTypeList.value.length * 90;
    if (pageContentWidth.value - t < w) {
      return w;
    } else {
      return pageContentWidth.value - t;
    }
  } else {
    return pageContentWidth.value - 150 < w ? w : pageContentWidth.value - 150;
  }
});
const clickHandler = (row: any) => {
  const className = routerStore.getSubject.toLowerCase();
  const path = `/${className}/fab/provision/craft/relevancy`;
  const { technology = "", product = "", lot = "", wafer = "" } = queryParams;
  const p = searchRef.value.getParams();
  const { startTime = "", endTime = "", parameter = "", period = "" } = p;
  const query = { technology, product, lot, wafer, layerId: row.layer, routeId: row.routeId, startTime, endTime, parameter, period };
  // const params = { path, query };
  // const { href } = router.resolve(params);
  // window.open(href, "_blank");
  let params = encodeURI(JSON.stringify(query));
  const { href } = router.resolve({ path, query: { params } });
  window.open(href, "_blank");
};
const resize = () => {
  myChart && myChart.resize();
  rulerChart && rulerChart.resize();
};
onMounted(() => {
  getTechlogyList();
  getProductList();
  const {
    query: { params = "" }
  } = route;
  if (params) {
    const query = JSON.parse(decodeURI(params as string));
    if (query) {
      const { technology = "", product = "", lot = "", wafer = "", startTime = "", endTime = "", parameter = "", period = "" } = query;
      queryParams.technology = technology;
      queryParams.product = product;
      queryParams.lot = lot;
      queryParams.wafer = wafer;
      defaultSearchParams.startTime = startTime;
      defaultSearchParams.endTime = endTime;
      defaultSearchParams.parameter = parameter;
      defaultSearchParams.period = period;
    }
  }
  window.addEventListener("resize", resize);
  // getLotList();
  // getWaferList()

  // wafer 工艺流程
  // getFlowInfo();
  // 详细耗量
  // getSupplyConsume();
  // getTotalConsume();
});
onUnmounted(() => {
  if (rulerChart !== null && rulerChart !== undefined) {
    rulerChart.dispose();
  }
  if (myChart !== null && myChart !== undefined) {
    myChart.dispose();
  }
  window.removeEventListener("resize", resize);
});
</script>

<template>
  <div ref="pageRef" class="provision-craft">
    <ReTeleport placement="left" :width="182">
      <div class="provision-area-search">
        <search
          ref="searchRef"
          type="craft"
          :period="defaultSearchParams.period"
          :startTime="defaultSearchParams.startTime"
          :endTime="defaultSearchParams.endTime"
          :parameter="defaultSearchParams.parameter"
          @change="searchChangeHandler"
          @typeChange="typeChange"
          @areaChange="areaChange"
          @selectChange="searchSelectChange"
        />
      </div>
    </ReTeleport>
    <div ref="pageContentRef" class="provision-craft-content">
      <px-form ref="queryRef" class="custom-form-ui" :rules="rules" :model="queryParams" inline label-width="90px">
        <px-form-item label="工艺选择" prop="technology">
          <px-select v-model="queryParams.technology" clearable filterable>
            <px-option v-for="item in technologyList" :key="item.code" :label="item.name" :value="item.code" />
          </px-select>
        </px-form-item>

        <px-form-item label="产品选择" prop="product">
          <px-select v-model="queryParams.product" clearable filterable>
            <px-option v-for="item in productList" :key="item.code" :label="item.name" :value="item.code" />
          </px-select>
        </px-form-item>
        <px-form-item label="Lot编号" prop="lot">
          <px-select-v2
            v-model="queryParams.lot"
            remote
            :remote-method="getLotList"
            clearable
            reserve-keyword
            remote-show-suffix
            filterable
            :loading="lotLoading"
            :options="lotList"
          />
        </px-form-item>
        <px-form-item label="Wafer编号" prop="wafer">
          <px-select-v2
            v-model="queryParams.wafer"
            remote
            :remote-method="getWaferList"
            clearable
            reserve-keyword
            remote-show-suffix
            filterable
            :loading="waferLoading"
            :options="waferList"
          />
        </px-form-item>

        <px-form-item class="option-item">
          <px-button type="primary" @click="searchAction(false)">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </px-form-item>
      </px-form>

      <div class="chart-data-filter">
        <px-radio-group v-model="filterParams.groupType" @change="groupTypeChange">
          <px-radio label="LAYER">Layer</px-radio>
          <px-radio label="ROUTE">Route</px-radio
          ><!--style="margin-right: 10px"-->
          <!-- <px-select v-model="filterParams.routes" multiple collapse-tags collapse-tags-tooltip all-option
              ><px-option v-for="item in routeList" :key="item.routeId" :label="item.routeId" :value="item.routeId"
            /></px-select> -->
          <px-radio label="STEP">Step</px-radio
          ><!--style="margin-left: 16px"-->
        </px-radio-group>
        <div class="total-consume">{{ defaultSearchParams.parameterName }} 总耗量：{{ totalConsume.value }} {{ totalConsume.unit }}</div>
      </div>
      <px-table
        v-loading="loading"
        style="width: 100%"
        :data="tableData"
        :span-method="objectSpanMethod"
        border
        :cell-class-name="cellClassName"
        :row-class-name="rowClassName"
        class="disable-row-hover"
        show-overflow-tooltip
        :height="tableHeight"
      >
        <template #empty>
          <px-empty />
        </template>
        <!-- <px-table-column v-if="filterParams.groupType == 'LAYER'" prop="layer" label="" width="150" align="center" /> -->
        <px-table-column v-if="filterParams.groupType != 'ROUTE'" prop="layer" label="" width="150" align="center">
          <template #default="scope">
            <div @click="clickHandler(scope.row)">
              {{ scope.row.layer }}<br />
              <px-icon><Right /></px-icon>
            </div>
          </template>
        </px-table-column>
        <px-table-column v-if="filterParams.groupType == 'ROUTE'" prop="routeType" label="" width="150" align="center" />
        <px-table-column v-for="item in routeTypeList" :key="item.routeType" :prop="item.routeType" :label="item.routeType" width="90" align="center">
          <template #default="scope">
            <div
              v-if="scope.row.routeType == item.routeType && scope.row.areaId"
              :class="getClassName(scope.row.areaId)"
              @click="clickHandler(scope.row)"
            >
              <px-icon><Right /></px-icon>
            </div>
          </template>
        </px-table-column>

        <px-table-column v-if="filterParams.groupType == 'STEP'" prop="stepName" label="Step" width="120" align="center" />
        <px-table-column prop="dataChart" label="" :width="chartWidth" :show-overflow-tooltip="false">
          <template #header>
            <div id="ruler-chart" class="ruler-chart" />
            <div v-if="tableData.length" class="unit-info">{{ totalConsume.unit }}</div>
          </template>
          <template #default="scope">
            <!-- <div class="chart" :id="`chart_${scope.row.layerId }`" v-if="scope.row.isFirst"></div> -->
            <div v-if="scope.$index == 0" id="chart" class="chart" />
          </template>
        </px-table-column>
      </px-table>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.provision-craft {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 16px;
  overflow: hidden;
  background-color: #fff;

  .provision-craft-content {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    overflow: hidden;
    // padding: 16px;
    background: #fff;

    .fade-enter-active,
    .fade-leave-active {
      transition: opacity 0.6s;
    }

    .fade-enter-from,
    .fade-leave-to {
      opacity: 0;
    }
  }
}

.provision-area-search {
  box-sizing: border-box;
  width: 100%;
  padding: 0 16px 16px;
}

.chart-data-filter {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.total-consume {
  flex: 1;
  font-size: 16px;
  font-weight: bold;
  text-align: right;
}

:deep(.disable-row-hover) {
  .px-table__body tr:hover > td {
    background-color: inherit;
  }
}

.chart {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 1000;
  width: 100%;
  height: 100%;
}

.chart-wrapper {
  position: relative;
  width: 800px;
  height: 400px;
  border: 1px solid red;
}

:deep(.px-table) {
  th {
    background-color: var(--px-color-primary-light-9);
  }

  .cell {
    height: 40px;
    padding: 0;
    line-height: 40px;
  }

  .px-table__cell {
    height: 40px;
    padding: 0;
  }
}

:deep(.px-table .px-table__body) {
  .layer-row {
    .layer-column {
      text-align: center;
      cursor: pointer;
      background: #e7eefb;

      .cell {
        line-height: 23px;
      }
    }

    .route-type-column,
    .s-layer-column {
      background: #e7eefb;
    }

    &.layer-row-even {
      .layer-column,
      .route-type-column,
      .s-layer-column {
        background: #c7deff !important;
      }
    }
  }
}

:deep(.ruler-chart) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 200px;
}

:deep(.unit-info) {
  position: absolute;
  top: 13px;
  right: 10px;
  font-size: 12px;
}

// :deep(.data-chart-column) {
//   .cell {
//     position: absolute;
//     top: 0;
//     right: 0;
//     z-index: 1000;
//     width: 100%;
//     height: 100%;
//     padding: 0;
//   }
// }

.wfs {
  cursor: pointer;
  background-color: #ffeb1e;
}

.imp {
  cursor: pointer;
  background-color: #ff7280;
}

.litho {
  cursor: pointer;
  background-color: #ffa76f;
}

.pvd-back {
  cursor: pointer;
  background-color: #40fbff;
}

.pvd {
  cursor: pointer;
  background-color: #7800bd;
}

.cvd {
  cursor: pointer;
  background-color: #ffc132;
}

.cmp {
  cursor: pointer;
  background-color: #9dffbe;
}

.etch {
  cursor: pointer;
  background-color: #4da6ff;
}

.wet {
  cursor: pointer;
  background-color: #959dff;
}

.diff {
  cursor: pointer;
  background-color: #f279ff;
}

.rtp {
  cursor: pointer;
  background-color: #10b981;
}

.epi {
  cursor: pointer;
  background-color: #0054ff;
}
</style>
